<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Klein 智能图片识别系统</title>
    <script src="https://cdn.tailwindcss.com"></script>
    <link href="https://cdn.jsdelivr.net/npm/font-awesome@4.7.0/css/font-awesome.min.css" rel="stylesheet">
    <script>
        tailwind.config = {
            theme: {
                extend: {
                    colors: {
                        primary: '#165DFF',
                        secondary: '#36CFC9',
                        neutral: '#F5F7FA',
                        dark: '#1D2129',
                    },
                    fontFamily: {
                        inter: ['Inter', 'system-ui', 'sans-serif'],
                    },
                }
            }
        }
    </script>
    <style type="text/tailwindcss">
        @layer utilities {
            .content-auto {
                content-visibility: auto;
            }
            .shadow-soft {
                box-shadow: 0 4px 20px rgba(0, 0, 0, 0.08);
            }
            .transition-custom {
                transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
            }
        }
    </style>
</head>
<body class="font-inter bg-neutral min-h-screen flex flex-col">
    <!-- 导航栏 -->
    <header class="bg-white shadow-sm sticky top-0 z-50">
        <div class="container mx-auto px-4 py-4 flex justify-between items-center">
            <div class="flex items-center space-x-2">
                <i class="fa fa-eye text-primary text-2xl"></i>
                <h1 class="text-xl md:text-2xl font-bold text-dark">Klein 智能图片识别系统</h1>
            </div>
            <div class="hidden md:flex items-center space-x-6">
                <a href="#" class="text-gray-600 hover:text-primary transition-custom">首页</a>
                <a href="#" class="text-gray-600 hover:text-primary transition-custom">使用指南</a>
                <a href="#" class="text-gray-600 hover:text-primary transition-custom">关于我们</a>
            </div>
            <button class="md:hidden text-gray-600">
                <i class="fa fa-bars text-xl"></i>
            </button>
        </div>
    </header>

    <!-- 主要内容 -->
    <main class="flex-grow container mx-auto px-4 py-8 md:py-16">
        <div class="max-w-4xl mx-auto">
            <!-- 介绍部分 -->
            <div class="text-center mb-12">
                <h2 class="text-[clamp(1.5rem,3vw,2.5rem)] font-bold text-dark mb-4">图片智能识别与标注</h2>
                <p class="text-gray-600 max-w-2xl mx-auto">上传图片，我们的系统将自动识别图片内容并生成详细标注。支持多种图片格式，单张图片大小不超过10MB。</p>
            </div>

            <!-- 上传区域 -->
            <div id="upload-container" class="bg-white rounded-xl shadow-soft p-6 md:p-8 mb-8 transition-custom hover:shadow-lg">
                <div id="drop-area" class="border-2 border-dashed border-gray-300 rounded-lg p-8 text-center cursor-pointer transition-custom hover:border-primary/50 hover:bg-primary/5">
                    <input type="file" id="file-input" class="hidden" accept="image/*" />
                    <div class="flex flex-col items-center">
                        <i class="fa fa-cloud-upload text-5xl text-primary/70 mb-4"></i>
                        <h3 class="text-lg font-medium text-dark mb-2">拖放图片到此处，或点击上传</h3>
                        <p class="text-sm text-gray-500 mb-4">支持 JPG、PNG、WEBP 等格式，最大 10MB</p>
                        <button id="upload-btn" class="bg-primary hover:bg-primary/90 text-white px-6 py-2.5 rounded-lg transition-custom flex items-center">
                            <i class="fa fa-picture-o mr-2"></i>
                            选择图片
                        </button>
                    </div>
                </div>

                <!-- 预览区域 -->
                <div id="preview-container" class="mt-6 hidden">
                    <h4 class="font-medium text-dark mb-3">预览：</h4>
                    <div class="flex justify-center">
                        <img id="preview-image" class="max-w-full max-h-64 object-contain rounded-lg border border-gray-100" alt="图片预览">
                    </div>
                    <div class="mt-4 flex justify-center">
                        <button id="process-btn" class="bg-secondary hover:bg-secondary/90 text-white px-6 py-2.5 rounded-lg transition-custom flex items-center">
                            <i class="fa fa-cog mr-2"></i>
                            开始识别
                        </button>
                    </div>
                </div>
            </div>

            <!-- 进度条区域 -->
            <div id="progress-container" class="bg-white rounded-xl shadow-soft p-6 md:p-8 mb-8 hidden">
                <h3 class="text-lg font-medium text-dark mb-4">处理中...</h3>
                <div class="w-full bg-gray-200 rounded-full h-2.5 mb-2">
                    <div id="progress-bar" class="bg-primary h-2.5 rounded-full transition-all duration-300" style="width: 0%"></div>
                </div>
                <p id="progress-text" class="text-sm text-gray-500 text-right">0% 完成</p>
                <div class="mt-4 text-center text-gray-600">
                    <i class="fa fa-circle-o-notch fa-spin mr-2"></i>
                    <span>正在分析图片内容，请稍候...</span>
                </div>
            </div>

            <!-- 结果展示区域 -->
            <div id="result-container" class="bg-white rounded-xl shadow-soft p-6 md:p-8 mb-8 hidden">
                <h3 class="text-lg font-medium text-dark mb-6 flex items-center">
                    <i class="fa fa-check-circle text-secondary mr-2"></i>
                    识别结果
                </h3>
                
                <div class="grid md:grid-cols-2 gap-6">
                    <!-- 左侧：原图 -->
                    <div>
                        <h4 class="font-medium text-dark mb-3">原图：</h4>
                        <div class="bg-gray-50 rounded-lg p-2">
                            <img id="result-image" class="w-full rounded object-contain max-h-80" alt="识别结果图片">
                        </div>
                    </div>
                    
                    <!-- 右侧：标注信息 -->
                    <div>
                        <h4 class="font-medium text-dark mb-3">标注信息：</h4>
                        <div id="annotations" class="space-y-3 max-h-80 overflow-y-auto pr-2">
                            <!-- 标注结果将动态插入这里 -->
                        </div>
                    </div>
                </div>
                
                <div class="mt-6 flex justify-center">
                    <button id="new-upload-btn" class="bg-primary hover:bg-primary/90 text-white px-6 py-2.5 rounded-lg transition-custom">
                        上传新图片
                    </button>
                </div>
            </div>
        </div>
    </main>

    <!-- 页脚 -->
    <footer class="bg-white border-t border-gray-200 py-6">
        <div class="container mx-auto px-4 text-center text-gray-500 text-sm">
            <p>© 2025 Klein 智能图片识别系统 - 保留所有权利</p>
        </div>
    </footer>

    <script>
        // 获取DOM元素
        const fileInput = document.getElementById('file-input');
        const uploadBtn = document.getElementById('upload-btn');
        const dropArea = document.getElementById('drop-area');
        const previewContainer = document.getElementById('preview-container');
        const previewImage = document.getElementById('preview-image');
        const processBtn = document.getElementById('process-btn');
        const progressContainer = document.getElementById('progress-container');
        const progressBar = document.getElementById('progress-bar');
        const progressText = document.getElementById('progress-text');
        const resultContainer = document.getElementById('result-container');
        const resultImage = document.getElementById('result-image');
        const annotations = document.getElementById('annotations');
        const newUploadBtn = document.getElementById('new-upload-btn');
        
        let selectedFile = null;
        
        // 上传按钮点击事件
        uploadBtn.addEventListener('click', () => {
            fileInput.click();
        });
        
        // 文件选择事件
        fileInput.addEventListener('change', (e) => {
            if (e.target.files.length > 0) {
                handleFile(e.target.files[0]);
            }
        });
        
        // 拖放事件
        ['dragenter', 'dragover', 'dragleave', 'drop'].forEach(eventName => {
            dropArea.addEventListener(eventName, preventDefaults, false);
        });
        
        function preventDefaults(e) {
            e.preventDefault();
            e.stopPropagation();
        }
        
        ['dragenter', 'dragover'].forEach(eventName => {
            dropArea.addEventListener(eventName, highlight, false);
        });
        
        ['dragleave', 'drop'].forEach(eventName => {
            dropArea.addEventListener(eventName, unhighlight, false);
        });
        
        function highlight() {
            dropArea.classList.add('border-primary');
            dropArea.classList.add('bg-primary/10');
        }
        
        function unhighlight() {
            dropArea.classList.remove('border-primary');
            dropArea.classList.remove('bg-primary/10');
        }
        
        dropArea.addEventListener('drop', handleDrop, false);
        
        function handleDrop(e) {
            const dt = e.dataTransfer;
            const file = dt.files[0];
            handleFile(file);
        }
        
        // 处理选中的文件
        function handleFile(file) {
            // 检查文件类型
            if (!file.type.startsWith('image/')) {
                alert('请上传图片文件！');
                return;
            }
            
            // 检查文件大小 (10MB)
            if (file.size > 10 * 1024 * 1024) {
                alert('文件大小不能超过10MB！');
                return;
            }
            
            selectedFile = file;
            
            // 显示预览
            const reader = new FileReader();
            reader.onload = (e) => {
                previewImage.src = e.target.result;
                previewContainer.classList.remove('hidden');
            };
            reader.readAsDataURL(file);
        }
        
        // 处理图片识别
        processBtn.addEventListener('click', () => {
            if (!selectedFile) return;
            
            // 显示进度条
            previewContainer.classList.add('hidden');
            progressContainer.classList.remove('hidden');
            
            // 模拟进度更新
            simulateProgress();
            
            // 创建FormData对象
            const formData = new FormData();
            formData.append('image', selectedFile);
            
            // 发送图片到后端
            fetch('/api/recognize', {
                method: 'POST',
                body: formData
            })
            .then(response => {
                if (!response.ok) {
                    throw new Error('识别失败');
                }
                return response.json();
            })
            .then(data => {
                // 显示结果
                showResult(data);
            })
            .catch(error => {
                console.error('Error:', error);
                alert('处理图片时出错，请重试！');
                resetUI();
            });
        });
        
        // 模拟进度更新（实际应用中可根据后端进度更新）
        function simulateProgress() {
            let progress = 0;
            const interval = setInterval(() => {
                progress += Math.random() * 10;
                if (progress >= 100) {
                    progress = 100;
                    clearInterval(interval);
                }
                progressBar.style.width = `${progress}%`;
                progressText.textContent = `${Math.round(progress)}% 完成`;
            }, 300);
        }
        
        // 显示识别结果
        function showResult(data) {
            progressContainer.classList.add('hidden');
            resultContainer.classList.remove('hidden');
            
            // 显示结果图片 - 修复图片显示问题
            if (data.image_url && data.image_url !== '') {
                resultImage.src = data.image_url;
            } else {
                // 如果后端没有返回图片URL，则使用预览图片
                resultImage.src = previewImage.src;
            }
            
            // 清空之前的标注
            annotations.innerHTML = '';
            
            // 添加标注信息
            data.annotations.forEach(annotation => {
                const annotationEl = document.createElement('div');
                annotationEl.className = 'p-3 bg-gray-50 rounded-lg border border-gray-100';
                
                annotationEl.innerHTML = `
                    <div class="flex justify-between items-start">
                        <div>
                            <h5 class="font-medium text-dark">${annotation.label}</h5>
                            <p class="text-sm text-gray-600 mt-1">置信度: ${(annotation.confidence * 100).toFixed(1)}%</p>
                        </div>
                        <span class="px-2 py-1 bg-primary/10 text-primary text-xs rounded-full">
                            ${annotation.category}
                        </span>
                    </div>
                    ${annotation.description ? `<p class="text-sm text-gray-500 mt-2">${annotation.description}</p>` : ''}
                `;
                
                annotations.appendChild(annotationEl);
            });
        }
        
        // 上传新图片
        newUploadBtn.addEventListener('click', () => {
            resetUI();
            fileInput.value = '';
            selectedFile = null;
        });
        
        // 重置UI
        function resetUI() {
            resultContainer.classList.add('hidden');
            progressContainer.classList.add('hidden');
            previewContainer.classList.add('hidden');
            progressBar.style.width = '0%';
            progressText.textContent = '0% 完成';
        }
    </script>
</body>
</html>
